<?php

class Sistema_UsuariosController extends App_Controller_Action
{
    private $_table     = 'USUARIOS';
    private $_pk        = 'USU_ID';
    private $_order_col = 'USU_DATCAD';
    private $_order     = 'ASC';
    private $_sta_col   = 'USU_STA';
    private $obj        = '';
    private $form       = '';
    //public  $db = '';
    
    private $_PER_ID;
    private $_USU_ID;
    private $_USU_TPO = 1; // user sistema
     
    public function init()
    {   
        //$this->db = Zend_Db_Table_Abstract::getDefaultAdapter();
        $this->obj = new Sistema_Model_DbTable_Usuarios();
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Usuarios();
        
        $this->_PER_ID = Zend_Auth::getInstance()->getStorage()->read()->PER_ID;
        $this->_USU_ID = Zend_Auth::getInstance()->getStorage()->read()->USU_ID;
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        
        
        $where = 'USU_TPO = '.$this->_USU_TPO;
        if($this->_PER_ID <> 1){ // <> de administrador
            $where .= ' and USU_ID = '.$this->_USU_ID; // usuario logado
        }
        
        $USU_STA = $this->_getParam('USU_STA', 1);
        $where .= ' and USU_STA = '.$USU_STA;
        
        $obj = new Sistema_Model_DbTable_Usuarios();
        $result = $obj->fetchAll($where);
        $this->view->result = $this->paginacao($result);
    }
    
    
    public function editAction() {
        $form = new Sistema_Form_Usuarios();
        $form->submit->setLabel('Gravar');

        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if ($form->isValid($formData)) {
                    $id = (int) $form->getValue('USU_ID');
                    $data = array(
                        'USU_ID'        => $form->getValue('USU_ID'),
                        'USU_LOGIN'     => $form->getValue('USU_LOGIN'),	
                        //'USU_SENHA'     => sha1($form->getValue('USU_SENHA')),	
                        'USU_NOME'      => $form->getValue('USU_NOME'),
                        'USU_EMAIL'     => $form->getValue('USU_EMAIL'),
                        'PER_ID'        => $form->getValue('PER_ID'),
                        'USU_DATCAD'=> date('Y-m-d'),
                        'USU_TPO'       => $this->_USU_TPO,
                        'USU_CADSTA'    => 1,
                        'USU_STA'       => $form->getValue('USU_STA'), 
                        'USU_TEL'       => $form->getValue('USU_TEL'), 
                    );

                    if(strlen($form->getValue('USU_SENHA')) > 1){
                        $data['USU_SENHA'] = sha1($form->getValue('USU_SENHA'));
                    }
                    $obj = new Sistema_Model_DbTable_Usuarios();

                    if ($id == 0)
                        $obj->insert($data);
                    else
                        $obj->update($data, 'USU_ID = ' . $id);

                    $this->_helper->redirector('index');
                } else {
                    $form->populate($formData);
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.Errordb::descricaoError($ex->getCode()).'");</script>';
                //echo $ex->getCode().'<br>';       
                //echo $ex->getMessage().'<br>';
                $form->populate($formData);
            }
        } else {
            $id = $this->_getParam('id', 0);
            
            if($this->_PER_ID <> 1){ // <> de administrador
                if($this->_USU_ID <> $id){ // <> cod usuário logado
                    $this->_helper->redirector('index');
                }
            }
            
            if ($id > 0) {
                $obj = new Sistema_Model_DbTable_Usuarios();
                $form->populate($obj->fetchRow('USU_ID = ' . $id)->toArray());
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $obj = new Sistema_Model_DbTable_Usuarios();
            //$ok = (bool) $obj->delete('USU_ID = '.(int)$id);
            $data = array('USU_STA' => 0);
            $ok = (bool) $obj->update($data, 'USU_ID = ' . $id);
        }
        
        echo json_encode(array('ok' => $ok));
    }
    
    public function cpfdplAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = '';
        
        $id = $this->_getParam('id', 0);
        $cpf = $this->_getParam('cpf', '');
        $op = $this->_getParam('op', '');
        
        if($id > 0 && strlen($cpf) > 1){
            $where = 'USU_ID <> '.$id.' and USU_CPF = "'.$cpf.'"';
            $result = $this->obj->fetchAll($this->obj->select()->where($where)->order($this->_order_col.' '.$this->_order));

            foreach($result as $res){
                if($res->USU_CPF == $cpf){
                    $ok = TRUE;
                    $msg = 'CPF já utilizado';
                }
            }
        }
        
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }

}